package com.rao.travel.dao;

import com.rao.travel.pojo.Role;
import com.rao.travel.pojo.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author Srao
 * @version 1.0
 * @className UserDao
 * @date 2019/10/30 22:38
 * @package com.rao.travel.dao
 * @description
 */
@Mapper
public interface UserDao {

    /*根据用户名查询用户*/
    @Select("select * from users where username = #{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class, many = @Many(select = "com.rao.travel.dao.RoleDao.findByUserId"))
    })
    UserInfo findByUsername(String username) throws Exception;

    /*查询所有用户*/
    @Select("select * from users")
    List<UserInfo> findAll();

    /*保存一个用户*/
    @Insert("insert into users(email, username, password, phoneNum, status) values (#{email}, #{username}, #{password}, #{phoneNum}, #{status})")
    void save(UserInfo userInfo);

    /*根据用户id查询用户*/
    @Select("select * from users where id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class, many = @Many(select = "com.rao.travel.dao.RoleDao.findByUserId")),
    })
    UserInfo findById(String id);

    /*查询该用户没有的角色*/
    @Select("select * from role where id not in (select roleId from users_role where userId = #{id})")
    List<Role> findOtherRole(UserInfo userInfo);

    /*为用户添加角色*/
    @Insert("insert into users_role(userId, roleId) values (#{userId}, #{roleId})")
    void addRoleToUser(@Param(value = "userId") String userId, @Param(value = "roleId") String roleId);
}
